package com.spring;

import com.dq.DuXiaoQTestApplication;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: AnnotationConfigApplicationContext
 * @Description: spring容器主启动类 Main方法入口
 * @Author: spring-source_小强 (QQ:2680825683)
 * @Since: 2023/5/8 8:54
 */
public class AnnotationConfigApplicationContext {
    //扫描config
    private Class config;

    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>(); // 单例池
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(); // 所有bean定义（scope）
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>(); //bean初始化环绕

    //构造方法
    public AnnotationConfigApplicationContext(Class appConfig) {
        this.config = appConfig;

        //扫描components
        scanComponents();

        //根据 beanDefinitionMap 所有bean类型 把单例bean放入单例池
        for (Map.Entry<String, BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if (beanDefinition.getScope().equals("singleton")) {
                Object singleBeanInstance = creatBean(beanName, beanDefinition);
                singletonObjects.put(beanName, singleBeanInstance); //存放
            }
        }
    }

    /**
     * 创建Bean实例化 同时把属性注入  **递归创建Bean+Filed注入**
     * 单例就直接放入Map下次直接拿就用  |  原型bean就每次都creat一个
     * 进行Autowired的注入
     *
     * @param beanDefinition bean对象的信息
     * @return Obj
     */
    public Object creatBean(String beanName, BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getClazz();
        try {
            Object classConstructInstance = clazz.getDeclaredConstructor().newInstance();

            //依赖注入 把依赖属性遍历注入
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(Autowired.class)) {
                    Object bean = getBean(field.getName());
                    field.setAccessible(true);
                    field.set(classConstructInstance, bean);
                }
            }

            //beanName注入
            if (classConstructInstance instanceof BeanNameAware) {
                ((BeanNameAware) classConstructInstance).setBeanName(beanName);
            }

            //前置beanPostProcessorList
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                classConstructInstance = beanPostProcessor.postProcessBeforeInitialization(classConstructInstance, beanName);
            }

            //Init
            if (classConstructInstance instanceof InitializingBean) {
                try {
                    ((InitializingBean) classConstructInstance).afterPropertiesSet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                classConstructInstance = beanPostProcessor.postProcessAfterInitialization(classConstructInstance, beanName);
            }

            return classConstructInstance;
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据ComponentScan扫描组件
     */
    private void scanComponents() {
        //解析配置类
        ComponentScan componentScanAnnotation = (ComponentScan) config.getDeclaredAnnotation(ComponentScan.class);
        String scanPath = componentScanAnnotation.value(); //获取扫描路径
        scanPath.replace(".", "/");
        ClassLoader classLoader = DuXiaoQTestApplication.class.getClassLoader();
        URL resource = classLoader.getResource("com/dq/service");
        File file = new File(resource.getFile());
        File[] files = file.listFiles();
        for (File f : files) {
            //加载Component组件 进一步操作
            String filePath = f.getAbsolutePath();
            if (filePath.endsWith(".class")) {
                String className = filePath.substring(filePath.indexOf("com\\"), filePath.lastIndexOf("."));
                className = className.replace("\\", ".");
                // System.out.println("className = " + className);
                try {
                    Class<?> clazz = classLoader.loadClass(className);
                    if (clazz.isAnnotationPresent(Component.class)) {

                        //解析BeanPostProcessor
                        if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                            BeanPostProcessor instance = (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                            beanPostProcessorList.add(instance);
                        }


                        //解析一个class 生成一个BeanDefinition
                        Component componentAnnotation = clazz.getDeclaredAnnotation(Component.class);
                        String beanName = componentAnnotation.value();

                        BeanDefinition beanDefinition = new BeanDefinition();
                        if (clazz.isAnnotationPresent(Scope.class)) {
                            Scope scopeAnnotation = clazz.getDeclaredAnnotation(Scope.class);
                            beanDefinition.setScope(scopeAnnotation.value());
                        } else {
                            beanDefinition.setScope("singleton");
                        }
                        beanDefinition.setClazz(clazz);
                        beanDefinitionMap.put(beanName, beanDefinition);

                    }
                } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException |
                         InstantiationException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 获取容器
     *
     * @param beanName 容器Name
     * @return
     */
    public Object getBean(String beanName) {
        if (beanDefinitionMap.containsKey(beanName)) {
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if (beanDefinition.getScope().equals("singleton")) { //单例池获取bean
                return singletonObjects.get(beanName);
            } else {
                return creatBean(beanName, beanDefinition);
            }
        } else {
            //不存在bean对象
            throw new NullPointerException();
        }
    }
}
